#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import request, Blueprint
import orjson


class LJVaildRule:
    def __init__(self, field: str, required: bool):
        self.field = field
        self.required = required


def lj_flask_valid(*rules: LJVaildRule):
    """参数校验函数"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            # 参数校验
            req_params = get_merge_param()
            for rule in rules:
                if rule.required and not req_params.get(rule.field):
                    raise Exception(f'参数[{rule.field}]不能为空...')

            res = func(*args, **kwargs)
            return res
        return wrapper
    return decorator


def get_merge_param():
    req_data = {}
    req_data.update(request.args or {})
    req_data.update(request.form or {})

    raw_data = request.get_data(as_text=True)
    if raw_data:
        req_data.update(orjson.loads(raw_data))

    return req_data


def get_param(key):
    return get_merge_param().get(key)
